package com.hddf.project.auth.service;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public class CookieService {
	private static CookieService cookie_service = null;
	private static volatile String domain = ".kamixy.cn";
	//private static UserDao_MongoDB user_dao_mongodb = null;
	//令牌有效时间 单位是 秒 默认是 3600秒 (1小时)
	//private static final long apptoken_lifetime = 60*60 ;
	static {
		if(cookie_service==null){
			cookie_service = new CookieService();
		}
		/*if(user_dao==null){
			user_dao = new UserDaoImpl();
		}
		if(user_dao_mongodb==null){
			user_dao_mongodb = new UserDaoImpl_MongoDB();
		}*/
	}
	
	public static CookieService getInstance(){
		return cookie_service;
	}
	
	/**
	 * 设置cookie
	 * @param response
	 * @param name  cookie名字
	 * @param value cookie值
	 * @param maxAge cookie生命周期  以秒为单位
	 */
	public void addCookie(HttpServletResponse response,String name,String value,int maxAge){
		
	    Cookie cookie = new Cookie(name,value);
	    //设置路径，这个路径即该工程下都可以访问该cookie 如果不设置路径，那么只有设置该cookie路径及其子路径可以访问
	    cookie.setPath("/");
	    //设置域 
	    cookie.setDomain(domain);
	    if(maxAge>0)  cookie.setMaxAge(maxAge);
	    response.addCookie(cookie);
	}
	
	/**
	 * 根据名字获取cookie
	 * @param request
	 * @param name cookie名字
	 * @return
	 */
	public Cookie getCookieByName(HttpServletRequest request,String name){
	    Map<String,Cookie> cookieMap = ReadCookieMap(request);
	    if(cookieMap.containsKey(name)){
	        Cookie cookie = (Cookie)cookieMap.get(name);
	        return cookie;
	    }else{
	        return null;
	    }   
	}
	
	/**
	 * 将cookie封装到Map里面
	 * @param request
	 * @return
	 */
	private  Map<String,Cookie> ReadCookieMap(HttpServletRequest request){  
	    Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
	    Cookie[] cookies = request.getCookies();
	    if(null!=cookies){
	        for(Cookie cookie : cookies){
	            cookieMap.put(cookie.getName(), cookie);
	        }
	    }
	    return cookieMap;
	}

	public static void setDomain(String domain) {
		System.out.println("set cookie domain "+domain);
		CookieService.domain = domain;
	}

}
